import { useState, useRef, useEffect } from 'react'
import UseReplaceWord from './UseReplaceWord'
import axios from 'axios'
import { formatTime } from '@/views/hooks/UseFormatTime.ts'
import InfiniteScroll from 'react-infinite-scroll-component'
const headers = {
  Authorization:
    'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Imp5a2wiLCJ1c2VySWQiOjQ3NTI5NTU1LCJyb2xlIjoxLCJpYXQiOjE3MzUyMDkzNjAsImV4cCI6MTczNzgwMTM2MH0.wI_YlirqF_DKrw0hSmDxoWDpJRlReaC84ohbf39fkJs',
}
function CommentContent() {
  // 评论列表数据
  const [commentList, setCommentList] = useState([])
  const [userName, setUserName] = useState('')
  const [hasMore, setHasMore] = useState(true)

  // const {formatDate, setTimeStr} = useFormTime()
  //新发表的品论内容
  const [userContent, setUserContent] = useState('')
  const words = ['TMD', '密码', '打人了']
  const newContent = UseReplaceWord(userContent, words)
  console.log('newStr', newContent)
  //设置用户名 或内容
  const handleForm = (e) => {
    const con = e.target.value
    console.log('con', con)
    if (e.target.name === 'userName') setUserName(con)
    else if (e.target.name === 'userContent') setUserContent(con)
  }
  //回复评论
  const replyHande = ({ id, content }) => {
    const params = {
      content,
      commentId: id,
      articleId: 89,
    }
    addComment(params)

    //    const arr =  commentList.map(item=>{
    //         if(item.id === id){
    //             const newItem = JSON.parse(JSON.stringify(item))
    //            newItem.replies.push(
    //             {
    //                 id: self.crypto.randomUUID(),
    //                 name:'niming',
    //                 content,
    //              }
    //            )
    //            return newItem
    //         }
    //         return  item
    //     })

    // setCommentList(arr)
  }
  //发表评论及回复
  const addComment = (params) => {
    const useInfor = JSON.parse(localStorage.getItem('userInfo'))
    // const item = {
    //     id:commentList.length+1,
    //     name:useInfor.username,
    //     content:newContent,
    //     createdAt: formatTime(Date.now())
    // }

    // const params = {
    //     userId:useInfor.userId,
    //     content:newContent,
    //     articleId:90
    // }
    params = { ...params, userId: useInfor.userId }

    axios
      .post('http://blogapi.shbwyz.com/discuss', params, { headers })
      .then((res) => {
        setCommentList(res.data.rows)
        setUserContent('')
      })
      .catch((err) => err)
  }

  useEffect(() => {
    axios.get('http://blogapi.shbwyz.com/article/89').then((res) => {
      const comments = res.data.comments
      console.log('comments', comments)
      setCommentList(comments)
    })
  }, [])
  //发表评论的组件
  const getPublishCom = () => {
    return (
      <div>
        {/* <input
                 className="user"
                type="text"
                placeholder="请输入昵称"
                value={userName}
                name="userName"
                onChange={handleForm}
                />
                <br /> */}
        <textarea
          className="content"
          cols="30"
          rows="10"
          placeholder="请输入评论内容"
          value={userContent}
          name="userContent"
          onChange={handleForm}
        ></textarea>
        <br />
        <button
          onClick={() => {
            const params = {
              content: newContent,
              articleId: 89,
            }
            addComment(params)
          }}
        >
          发表评论
        </button>
      </div>
    )
  }
  // 展示评论的子组件
  const Comment = ({ item, reply, isChild }) => {
    const { user, content, replies, createdAt } = item
    const [isShow, setIsShow] = useState(false)
    const txtArea = useRef(null)
    const name = user.username

    return (
      <>
        <h3>{name}:</h3>
        <p>{content}</p>
        <p>日期：{createdAt}</p>
        {!isChild && (
          <p>
            <button onClick={() => setIsShow(!isShow)}>回评论</button>
          </p>
        )}
        {isShow ? (
          <div>
            <textarea
              className="content"
              cols="30"
              rows="5"
              placeholder="请输入评论内容"
              name="Content"
              ref={txtArea}
            ></textarea>
            <br />
            <button
              onClick={() =>
                reply({ id: item.id, content: txtArea.current.value })
              }
            >
              回复
            </button>
          </div>
        ) : null}

        {replies?.length ? (
          <div style={{ border: '1px solid blue', marginLeft: '20px' }}>
            {replies.map((obj) => (
              <Comment item={obj} isChild={true} />
            ))}
          </div>
        ) : null}
      </>
    )
  }
  // 获取更多 评论
  const fetchMoreData = () => {
    //模拟数据
    const tempArr = [
      {
        createdAt: '2024-12-27 17:02:46',
        id: 61,
        content: '我在枯**要我是测试的我是第二次加载的',
        replies: [],
        user: {
          createdAt: '2024-12-21 10:50:38',
          id: 47529555,
          username: 'jykl',
          email: 'jykl@163.com',
          notice: true,
          role: 1,
          github: null,
          disabledDiscuss: false,
        },
      },
      {
        createdAt: '2024-12-27 17:01:44',
        id: 60,
        content: '*** 有厅厅要我是会么***s在枯**要',
        replies: [],
        user: {
          createdAt: '2024-12-21 10:50:38',
          id: 47529555,
          username: 'jykl',
          email: 'jykl@163.com',
          notice: true,
          role: 1,
          github: null,
          disabledDiscuss: false,
        },
      },
      {
        createdAt: '2024-12-27 16:59:19',
        id: 59,
        content: '打人了 有厅厅要我是会么TMDs在枯密码要 ',
        replies: [],
        user: {
          createdAt: '2024-12-21 10:50:38',
          id: 47529555,
          username: 'jykl',
          email: 'jykl@163.com',
          notice: true,
          role: 1,
          github: null,
          disabledDiscuss: false,
        },
      },
      {
        createdAt: '2024-12-27 15:56:25',
        id: 58,
        content: '我发表一个评论，测试',
        replies: [],
        user: {
          createdAt: '2024-12-21 10:50:38',
          id: 47529555,
          username: 'jykl',
          email: 'jykl@163.com',
          notice: true,
          role: 1,
          github: null,
          disabledDiscuss: false,
        },
      },
      {
        createdAt: '2024-12-25 15:55:04',
        id: 56,
        content: 'asssaas',
        replies: [
          {
            createdAt: '2024-12-26 18:05:51',
            id: 30,
            content: '我是回复的消息',
            user: {
              createdAt: '2024-12-21 10:50:38',
              id: 47529555,
              username: 'jykl',
              email: 'jykl@163.com',
              notice: true,
              role: 1,
              github: null,
              disabledDiscuss: false,
            },
          },
        ],
        user: {
          createdAt: '2024-12-21 10:50:38',
          id: 47529555,
          username: 'jykl',
          email: 'jykl@163.com',
          notice: true,
          role: 1,
          github: null,
          disabledDiscuss: false,
        },
      },
      {
        createdAt: '2024-12-21 10:51:20',
        id: 55,
        content: 'atest',
        replies: [],
        user: {
          createdAt: '2024-12-21 10:50:38',
          id: 47529555,
          username: 'jykl',
          email: 'jykl@163.com',
          notice: true,
          role: 1,
          github: null,
          disabledDiscuss: false,
        },
      },
    ]

    setCommentList((pre) => [ ...pre,...tempArr])
    setHasMore(false)
  }
  return (
    <div>
      {getPublishCom()}
      <InfiniteScroll
        // 数据长度
        dataLength={commentList.length}
        next={fetchMoreData}
        height={350}
        // 是否还有可加载滴数据
        hasMore={hasMore}
        scrollThreshold="20px"
        // 加载提示信息
        loader={
          <h4 style={{ textAlign: 'center', color: '#c72c31' }}>加载中...</h4>
        }
        // 加载结束提示信息
        endMessage={
          <p style={{ textAlign: 'center', color: '#c72c31' }}>
            <b>没有更多了~</b>
          </p>
        }
      >
        <ul>
          {commentList.map((item) => {
            const { id } = item
            return (
              <li key={id}>
                <Comment item={item} reply={replyHande} />
              </li>
            )
          })}
        </ul>
      </InfiniteScroll>
    </div>
  )
}

export default CommentContent
